package com.hgs.iias.web.action;

import org.springframework.beans.factory.annotation.Required;

import com.googlecode.jsonplugin.annotations.JSON;

import com.hgs.iias.domain.Application;
import com.hgs.iias.service.ApplicationService;

import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;


public class ApplicationAction extends ActionSupport implements ModelDriven<Application> {
	private static final long serialVersionUID = 4104711726510973493L;
	
	private Application        application = new Application();
	private Application[]      applications;
	private ApplicationService applicationService;
	
	public void setEntityClass(Class<? extends Application> clazz) throws IllegalAccessException, InstantiationException {
		application = clazz.newInstance();
	}
	
	@Required
	public void setApplicationService(ApplicationService applicationService) {
		this.applicationService = applicationService;
	}
	
	@JSON(name = "data")
	public Application getModel() {
		return application;
	}
	
	public Application[] getRecords() {
		return applications;
	}
	
	public boolean isSuccess() {
		return true;
	}
	
	public String apply() {
		try {
			applicationService.apply(getModel());
		} catch(Exception e) {
			return ERROR;
		}
		
		return SUCCESS;
	}
	
	public String list() {
		try {
			applications = applicationService.list().toArray(new Application[0]);
		} catch(Exception e) {
			return ERROR;
		}
		
		return SUCCESS;
	}
	
	public String submit() {
		try {
			applicationService.submit(applicationService.view(getModel().getId()));
		} catch(Exception e) {
			return ERROR;
		}
		
		return SUCCESS;
	}
	
	public String view() {
		try {
			application = applicationService.view(getModel().getId());
		} catch(Exception e) {
			return ERROR;
		}
		
		return SUCCESS;
	}
}
